import { StationService } from "admin/services/station";
import { parseUrlParams, formatDateTime } from "share/common";
import { MobilePageDisplay } from "admin/controls/mobilePageDisplay";
import { siteMap } from "admin/pageNodes";
import * as w from 'myWuZhui';
import React = require("react");
import ReactDOM = require("react-dom");
import * as wuzhui from "maishu-wuzhui";
import site from "admin/site";
import { PageProps } from "maishu-chitu-react";

site.loadCSS(siteMap.nodes.station_snapshoots.name);
export default class SnapshootList extends React.Component<PageProps, { selectedItem?: PageData, pageData?: PageData }> {
    mobilePageDisplater: MobilePageDisplay;
    snapshootTable: HTMLTableElement;
    pageDataId: string;
    constructor(props) {
        super(props);
        this.state = {};
        let urlParams = location.hash.split('?')[1];
        let params = parseUrlParams(urlParams);
        this.pageDataId = params.pageDataId;
    }
    async showSanpshoot(dataItem: PageData) {
        let station = this.props.app.createService(StationService);
        let pageData = await station.pageDataById(dataItem.id);
        this.mobilePageDisplater.changePageData(pageData);
        // this.state.pageData = pageData;
        // this.state.selectedItem = dataItem;
        // this.setState(this.state);
        this.setState({ pageData, selectedItem: dataItem })
    }
    recover(snapshootId: string) {
        let station = this.props.app.createService(StationService);
        return station.recoverFromSnapshoot(this.pageDataId, snapshootId);
    }
    componentDidMount() {
        let station = this.props.app.createService(StationService);
        let dataSource = new wuzhui.DataSource<PageData>({
            primaryKeys: ['id'],
            select(args) {
                let urlParams = location.hash.split('?')[1];
                let params = parseUrlParams(urlParams);
                return station.snapshootList(params.pageDataId, args);
            },
            delete(dataItem: PageData) {
                return station.deletePageData(dataItem.id);
            }
        })
        let gridView = w.createGridView({
            element: this.snapshootTable,
            dataSource,
            columns: [
                new w.BoundField({ dataField: 'id', headerText: '名称', visible: false }),
                new w.BoundField({ dataField: 'createDateTime', headerText: '日期', dataFormatString: '{g}' }),
                new w.CustomField({
                    createItemCell: (dataItem: PageData) => {
                        let cell = new wuzhui.GridViewCell();
                        ReactDOM.render([
                            <button key={10} className="btn btn-minier btn-info"
                                ref={(e: HTMLButtonElement) => {
                                    if (!e) return;
                                    ui.buttonOnClick(e, () => {
                                        return this.showSanpshoot(dataItem);
                                    })
                                }}>
                                <i className=" icon-folder-open-alt"></i>
                                <span>查看</span>
                            </button>,
                            <button key={20} className="btn btn-minier btn-success"
                                ref={(e: HTMLButtonElement) => {
                                    ui.buttonOnClick(e,
                                        () => this.recover(dataItem.id),
                                        { toast: '还原成功' }
                                    )
                                }}>
                                <i className="icon-undo"></i>
                                <span>还原</span>
                            </button>,
                            <button key={30} className="btn btn-minier btn-danger"
                                ref={(e: HTMLButtonElement) => {
                                    ui.buttonOnClick(e, () => {
                                        return dataSource.delete(dataItem);
                                    }, { confirm: `确定要删除该快照（${formatDateTime(dataItem.createDateTime)}）吗` })
                                }}>
                                <i className="icon-trash"></i>
                            </button>
                        ], cell.element)
                        return cell;
                    },
                    itemStyle: { textAlign: 'center' } as CSSStyleDeclaration,
                    headerStyle: { width: '180px' } as CSSStyleDeclaration,
                    headerText: "操作"
                })
            ],
            pageSize: 15
        })
        dataSource.selected.add((sender, result) => {
            if (this.state.selectedItem != null) {
                return;
            }

            this.showSanpshoot(result.dataItems[0]);
        })
    }
    render() {
        let { selectedItem } = this.state;
        let pageData = this.state.pageData || { controls: [] }
        return [
            <div key={20} >
                <ul style={{ margin: 0 }} className="clearfix">
                    <li className="pull-left">
                        <h4 style={{ marginBottom: 0 }}><b>快照列表</b></h4>
                    </li>
                    <li className="pull-right">
                        <button className="btn btn-sm btn-primary" onClick={() => this.props.app.back()}>
                            <i className="icon-reply" />
                            <span>返回</span>
                        </button>
                    </li>
                </ul>
                <hr style={{ margin: 0 }} />
                <div key={10} style={{ position: 'absolute', marginTop: 20 }}>
                    <MobilePageDisplay pageData={pageData}
                        displayMobile={false}
                        ref={(e) => this.mobilePageDisplater = e || this.mobilePageDisplater} />
                    <div style={{ position: 'absolute', width: 320, textAlign: 'center', marginTop: 20 }}>
                        <span>快照日期</span>
                        <span style={{ padding: "0 0 0 4px" }}>
                            {selectedItem ? formatDateTime(selectedItem.createDateTime) : ''}
                        </span>
                    </div>
                </div>
                <div style={{ paddingLeft: 340 }}>
                    <table className="table table-striped table-bordered table-hover"
                        ref={(e: HTMLTableElement) => this.snapshootTable = e || this.snapshootTable}>
                    </table>
                </div>
            </div>
        ]
    }
}